﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using AAEngine.Engine;
using AAEngine.Engine.Components;
using AAEngine.Engine.Resources;

namespace AAEngine.Sound
{
    /// <summary>
    /// Simple component to manage background music.
    /// </summary>
    public class BackgroundMusicComponent : TickedComponent
    {
        private bool _playing;
        private ISoundHandle _handle;

        public SoundResource Music { get; set; }

        private bool _autoStart = true;
        public bool AutoStart
        {
            get { return _autoStart; }
            set { _autoStart = value; }
        }

        public bool Playing
        {
            get { return _playing; }
        }

        public void Start()
        {
            _playing = true;

            if (_handle == null && Music == null)
            {
                return;
            }

            if (_handle == null)
            {
                _handle = AAGame.SoundManager.Play(Music, SoundManager.MUSIC_MIXER_CATEGORY, 0, 1);
            }
            else if (!_handle.IsPlaying)
            {
                _handle.Resume();
            }
        }

        public void Stop()
        {
            _playing = false;
            if (_handle != null)
            {
                _handle.Stop();
                _handle = null;
            }
        }

        public override void OnAdd()
        {
            base.OnAdd();

            if (AutoStart)
            {
                Start();
            }
        }

        public override void OnRemove()
        {
            base.OnRemove();

            Stop();
        }

        public override void OnTick(float deltaTime)
        {
            if (!_playing)
            {
                return;
            }

            if (_playing && _handle != null)
            {
                return;
            }

            if (Music == null)
            {
                return;
            }

            Start();
        }
    }
}
